import mjin2
import os

class Translator(object):
    def __init__(self, defaultLanguage):
        self.setDefaultLanguage(defaultLanguage)
        self.translatorDic = {}
    def defaultLanguage(self):
        return self.language
    def id(self, text, language = "default"):
        lan = language
        if (language == "default"):
            lan = self.language
        for key, value in self.translatorDic.items():
            if (lan in value):
                if (value[lan] == text):
                    return key
        return text
    def set(self, id, text, language = "default"):
        lan = language
        if (language == "default"):
            lan = self.language
        if (id in self.translatorDic):
            self.translatorDic[id][lan] = text
        else :
            self.translatorDic[id] = {lan : text}
    def setDefaultLanguage(self, language):
        self.language = language
    def tr(self, id, language = "default"):
        lan = language
        if (language == "default"):
            lan = self.language
        if (id in self.translatorDic):
            if (lan not in self.translatorDic[id]):
                lan = "en"
                if (lan not in self.translatorDic[id]):
                    return id
            return self.translatorDic[id][lan]
        return id

def loadTranslatorXML(translator, fileName):
    xml = mjin2.XML()
    node = xml.load(fileName)
    language = os.path.basename(fileName)[:os.path.basename(fileName).rfind(".")]
    s = node.nodes[0]
    for c in s.nodes:
        translator.set(c.attrs[0].value, c.nodes[0].value, language)

